import datetime
import time
from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info import user_login_data
from info.models import User, News, Category
from info.utils.image_storage import image_storage
from info.utils.response_code import RET
from . import admin_blue

@admin_blue.route('/add_category', methods=['POST'])
def add_category():
    category_id = request.json.get("id")
    category_name = request.json.get("name")

    if not category_name:
        return jsonify(errno=RET.NODATA,errmsg = "参数不全")

    if category_id:
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg = "获取分类失败")

        if not category:
            return jsonify(errno=RET.NODATA,errmsg = "分类不存在")

        category.name = category_name
    else:
        category = Category()
        category.name = category_name

        try:
            db.session.add(category)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR,errmsg = "分类创建失败")
    return jsonify(errno=RET.OK,errmsg = "操作成功")




@admin_blue.route('/news_category')
def news_category():
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "查询分类失败")

    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    return render_template("admin/news_type.html",categories=category_list)




@admin_blue.route('/news_edit_detail', methods=['GET', 'POST'])
def news_edit_detail():
    if request.method == "GET":
        news_id = request.args.get("news_id")
        if not news_id: return jsonify(errno=RET.PARAMERR,errmsg = "参数不全")
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg = "获取新闻失败")
        if not news: return jsonify(errno=RET.NODATA,errmsg = "新闻不存在")

        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg = "分类获取失败")

        category_list = []

        for category in categories:
            category_list.append(category.to_dict())

        return render_template("admin/news_edit_detail.html",news=news.to_dict(),categories=category_list)

    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    category_id = request.form.get("category_id")
    index_image = request.files.get("index_image")

    if not all([news_id,title,digest,content,category_id,index_image]):
        return jsonify(errno=RET.PARAMERR,errmsg = "参数不全")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    if not news: return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    try:
        image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg = "七牛云异常")
    if not image_name: return jsonify(errno=RET.NODATA,errmsg = "上传图片失败")
    try:
        news.title = title
        news.digest = digest
        news.content = content
        news.category_id = category_id
        news.index_image = constants.QINIU_DOMIN_PREFIX + image_name

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "修改失败")

    return jsonify(errno=RET.OK,errmsg = "修改成功")











@admin_blue.route('/news_edit')
def news_edit():
    page = request.args.get("p", "1")
    keywords = request.args.get("keywords")

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    try:
        filters = []

        if keywords:
            filters.append(News.title.contains(keywords))

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, 10, False)
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/news_edit.html", data={"errmsg": "新闻获取失败"})

    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())

    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_list": news_list
    }

    return render_template("admin/news_edit.html", data=data)





@admin_blue.route('/news_review_detail', methods=['GET', 'POST'])
def news_review_detial():
    if request.method == "GET":
        news_id = request.args.get("news_id")
        if not news_id: return jsonify(errno=RET.PARAMERR,errmsg = "参数不全")
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg = "获取新闻失败")
        if not news: return jsonify(errno=RET.NODATA,errmsg = "新闻不存在")

        return render_template("admin/news_review_detail.html",news=news.to_dict())

    news_id = request.json.get("news_id")
    action = request.json.get("action")

    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg = "参数不全")

    if not action in ["accept","reject"]:
        return jsonify(errno=RET.DATAERR,errmsg = "操作类型有误")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    if not news: return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    if action == "accept":
        news.status = 0
    else:
        news.reason = request.json.get("reason","")
        news.status = -1

    return jsonify(errno=RET.OK,errmsg = "新闻不存在")






@admin_blue.route('/news_review')
def news_review():
    page = request.args.get("p", "1")
    keywords = request.args.get("keywords")

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    try:
        filters = [News.status != 0]

        if keywords:
            filters.append(News.title.contains(keywords))

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, 10, False)
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/news_review.html", data={"errmsg": "新闻获取失败"})

    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())

    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_list": news_list
    }

    return render_template("admin/news_review.html", data=data)




@admin_blue.route('/user_list')
def user_list():
    page = request.args.get("p", "1")

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.create_time.desc()).paginate(page, 10, False)
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_list.html", data={"errmsg":"用户获取失败"})

    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    user_list = []
    for item in items:
        user_list.append(item.to_admin_dict())

    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "user_list": user_list
    }

    return render_template("admin/user_list.html", data=data)


@admin_blue.route('/user_count')
def user_count():
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_count.html",data = {"errmsg":"用户总数查询失败"})
    cal = time.localtime()
    try:
        start_mon_str = "%d-%d-01"%(cal.tm_year,cal.tm_mon)
        start_mon_date = datetime.datetime.strptime(start_mon_str,"%Y-%m-%d")
        mon_count = User.query.filter(User.last_login >= start_mon_date,User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_count.html", data={"errmsg": "用户月活查询失败"})

    try:
        start_day_str = "%d-%d-%d"%(cal.tm_year,cal.tm_mon,cal.tm_mday)
        start_day_date = datetime.datetime.strptime(start_day_str,"%Y-%m-%d")
        day_count = User.query.filter(User.last_login >= start_day_date,User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_count.html", data={"errmsg": "用户日活查询失败"})

    active_date = []
    active_count = []
    for i in range(0,7):
        begin_date = start_day_date - datetime.timedelta(days=i)
        end_date = start_day_date - datetime.timedelta(days=i-1)

        active_date.append(begin_date.strftime("%m-%d"))
        every_active_count = User.query.filter(User.is_admin==False,User.last_login>=begin_date,User.last_login<=end_date).count()
        active_count.append(every_active_count)

    active_date.reverse()
    active_count.reverse()



    data = {
       "total_count":total_count,
        "mon_count":mon_count,
        "day_count":day_count,
        "active_date":active_date,
        "active_count":active_count
    }
    return render_template("admin/user_count.html",data = data)






@admin_blue.route('/index')
@user_login_data
def index():
    admin = g.user.to_dict() if g.user else ""

    return render_template("admin/index.html",admin = admin)






@admin_blue.route('/login',methods=["GET","POST"])
def admin_login():
    if request.method == "GET":
        if session.get("is_admin"):
            return redirect(url_for("admin.index"))

        return render_template("admin/login.html")

    username = request.form.get("username")
    password = request.form.get("password")

    if not all([username,password]):
        return render_template("admin/login.html",errmsg = "参数不全")

    try:
        admin = User.query.filter(User.mobile == username,User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html",errmsg="管理员获取失败")
    if not admin:
        return render_template("admin/login.html",errmsg = "管理员不存在")

    if not admin.check_password(password):
        return render_template("admin/login.html",errmsg="密码错误")

    session["user_id"] = admin.id
    session["nick_name"] = admin.nick_name
    session["mobile"] = admin.mobile
    session["is_admin"] = True

    return redirect(url_for("admin.index"))
